/* File Server
 */

package main

import (
	"fmt"
//	"encoding/json"
	"net"
	"net/http"
	"os"
	"time"
	"flag"
	"regexp"
)

var (
  socketFile        *string = flag.String("SocketFile", "/tmp/webagent.sock", "The Unix domain socket file of webagent.") 
)

// Regular Http handler
type route struct {
  pattern *regexp.Regexp
  handler http.Handler
}

type RegexpHandler struct {
  routes []*route
}

func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) {
  h.routes = append(h.routes, &route{pattern, handler})
}

func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) {
  h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler)})
}

func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  for _, route := range h.routes {
    if route.pattern.MatchString(r.URL.Path) {
      route.handler.ServeHTTP(w, r)
      return
    }
  }
  // no pattern matched; send 404 response
  http.NotFound(w, r)
}

func main() {
	flag.Parse()
	laddr := net.UnixAddr{
		Net: "unix",
		Name: *socketFile,
	}
	listener, err := net.ListenUnix("unix", &laddr)
	checkError(err)
	defer listener.Close()

  var rh RegexpHandler
  var proxyReg *regexp.Regexp
  var exitReg *regexp.Regexp
  var roomReg *regexp.Regexp
  proxyReg, err = regexp.Compile("/proxy/*.")
  roomReg, err = regexp.Compile("/room/*.")
  exitReg, err = regexp.Compile("/exit")
  rh.HandleFunc(proxyReg, proxyCB)
  rh.HandleFunc(roomReg, roomCB)
  rh.HandleFunc(exitReg, exitCB)

	server :=  &http.Server{
    Handler:      &rh,
    ReadTimeout:  30*time.Second,
    WriteTimeout: 30*time.Second,
  }

  err = server.Serve(listener)
  checkError(err)
}

func checkError(err error) {
  if err != nil {
    fmt.Println("Fatal error ", err.Error())
    os.Exit(1)
  }
}

func proxyCB(writer http.ResponseWriter, req *http.Request) {
	fmt.Println("proxy received")
  writer.Write([]byte("OK"))
}
func roomCB(writer http.ResponseWriter, req *http.Request) {
	fmt.Println("room received")
  writer.Write([]byte("OK"))
}
func exitCB(writer http.ResponseWriter, req *http.Request) {
	fmt.Println("exit received")
  writer.Write([]byte("OK"))
}
